// pages/reservation/team.js
const app = getApp()
import api from '../../utils/api'

Page({
  data: {
    // 表单字段
    team_name: '',
    visit_date: '',
    visit_time: '',
    visitor_count: '', // 10-200
    contact_name: '',
    contact_phone: '',
    team_type_index: 0,
    team_type_options: ['学校', '企业', '社团', '政府机关', '社会团体', '其他'],
    purpose: '',
    special_requirements: '',

    // 日期选择范围
    startDate: '',
    endDate: '',

    canSubmit: false,
    submitting: false
  },

  onLoad() {
    this.setDateRange()
    this.prefillContact()
  },

  setDateRange(){
    try{
      const now = new Date()
      const end = new Date(now)
      end.setDate(end.getDate() + 60) // 未来60天
      const startDate = app.formatDate(now)
      const endDate = app.formatDate(end)
      this.setData({ startDate, endDate })
    }catch(e){}
  },

  prefillContact() {
    try {
      const user = app?.globalData?.userInfo || {}
      if (user) {
        this.setData({
          contact_name: this.data.contact_name || user.nickname || user.name || '',
          contact_phone: this.data.contact_phone || user.phone || ''
        })
      }
    } catch (e) {}
    this.updateCanSubmit()
  },

  // 输入框通用处理
  onInput(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({ [field]: value })
    this.updateCanSubmit()
  },

  onDateChange(e) {
    this.setData({ visit_date: e.detail.value })
    this.updateCanSubmit()
  },

  onTimeChange(e) {
    this.setData({ visit_time: e.detail.value })
    this.updateCanSubmit()
  },

  onTeamTypeChange(e) {
    this.setData({ team_type_index: Number(e.detail.value) })
    this.updateCanSubmit()
  },

  isValidPhone(phone) {
    return /^(1\d{10})$/.test(String(phone || '').trim())
  },

  updateCanSubmit() {
    const v = this.data
    const count = Number(v.visitor_count)
    const requireFilled = v.team_name && v.visit_date && v.visit_time && v.contact_name && this.isValidPhone(v.contact_phone)
    const countOk = Number.isFinite(count) && count >= 10 && count <= 200
    this.setData({ canSubmit: !!(requireFilled && countOk) })
  },

  async submit() {
    if (!this.data.canSubmit || this.data.submitting) return

    const isLoggedIn = await app.checkAuth()
    if (!isLoggedIn) return

    this.setData({ submitting: true })

    try {
      const payload = {
        team_name: this.data.team_name,
        visit_date: this.data.visit_date,
        visit_time: this.data.visit_time,
        visitor_count: Number(this.data.visitor_count),
        contact_name: this.data.contact_name,
        contact_phone: this.data.contact_phone,
        team_type: this.data.team_type_options[this.data.team_type_index],
        purpose: this.data.purpose,
        special_requirements: this.data.special_requirements
      }

      const res = await api.reservation.createTeam(payload)

      wx.showModal({
        title: '提交成功',
        content: (res && res.message) || '团队预约申请提交成功，请等待审核',
        showCancel: false,
        success: () => {
          wx.navigateTo({ url: '/pages/reservation/list' })
        }
      })
    } catch (err) {
      wx.showToast({ title: err.message || '提交失败', icon: 'none' })
    } finally {
      this.setData({ submitting: false })
    }
  }
})